# -*- coding: utf-8 -*-

# Define your item pipelines here
#
# Don't forget to add your pipeline to the ITEM_PIPELINES setting
# See: https://doc.scrapy.org/en/latest/topics/item-pipeline.html
import json
import pygal,codecs

class Homeworkmovietop100Pipeline(object):
    def __init__(self):
        self.json_file = open("movie_top100.json","wb+")
        self.json_file.write('[\n'.encode("UTF-8"))
    def close_spider(self, spider):
        print ("---------------关闭文件---------------")
        self.json_file.seek(-2,1)
        self.json_file.write('\n]'.encode("UTF-8"))
        self.json_file.close()
        
        #读取json绘制图表
        with codecs.open("movie_top100.json",'r','utf-8',buffering=True) as f:
            movie_list = json.load(f)
        movie_dict = {}
        #遍历列表，每个元素是一个电影信息
        #100个太多显示不全，只取前5个用于绘制图表。
        x_data = []
        y_data = []
        index = 0
        for movie in movie_list:
            x_data.append(movie["title"])
            y_data.append(movie["score"])
            bar = pygal.Bar()
            bar.add("电影评分",y_data)
            bar.x_labels = x_data
            bar.title = "电影top100"
            bar.x_title = "电影名"
            bar.y_title = "评分"
            bar.x_label_rotation = -60
            bar.legend_at_bottom = True
            bar.margin = 5
            bar.show_y_guides = False
            bar.show_x_guides = True
            bar.render_to_file("move_top100.svg")
            index += 1
            if index >= 5:
                break;
            
    def process_item(self, item, spider):
        print("标题：%s,%导演:%s,评分kk:%f",item["title"],item["director"],item["score"])
        #print("导演：",item["director"])
        #print("评分：",item["score"])
        #将item转换成json格式
        print ("text:111")
        dictText = dict(item)
        dumps = json.dumps(dictText,ensure_ascii=False)
        text = dumps + ",\n"
        print ("text:%s",text)
        #写入JSON到文件
        self.json_file.write(text.encode("UTF-8"))
        
        
        return item
